import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/repository/LocalMessageRepository.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/db/service/LocalMessageService.dart';
import 'package:easy_chat_app/commons/model/Conversation.dart';
import 'package:easy_chat_app/commons/model/OutboxMessage.dart';
import 'package:easy_chat_app/commons/model/Result.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:easy_chat_app/commons/ws/AppWSMessage.dart';
import 'package:logger/logger.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

Logger logger = Logger();

Future<void> newMsgProcess(AppWSMessage message) async {
  logger.i("message:$message");
  Result<List<OutboxMessage>> result =
      await HttpUtils.getNewOutboxMessageList();
  logger.i("result:$result");
  List<OutboxMessage> outboxMessageList = (result.data ?? []);
  if (outboxMessageList.isEmpty) {
    return;
  }
  outboxMessageList.sort((i1, i2) {
    return i1.id!.compareTo(i2.id!);
  });
  for (OutboxMessage outboxMessage in outboxMessageList) {
    LocalMessage localMessage = LocalMessage.create(
        conversationId: outboxMessage.conversationId,
        serverMsgId: outboxMessage.inboxMessageId,
        sourceUserId: outboxMessage.sourceUserId,
        targetUserId: outboxMessage.targetUserId,
        chatGroupId: outboxMessage.chatGroupId,
        chatType: 0,
        messageType: outboxMessage.messageType,
        message: outboxMessage.message,
        sendTime: outboxMessage.sendTime?.millisecondsSinceEpoch,
        status: LocalMessageStatusConstants.invalid,
        messageSource: LocalMessageMessageSourceConstants.outbox,
        readState: LocalMessageReadState.unread);
    await LocalMessageService.addLocalMessage(localMessage);
  }

  /// 会话最新消息map
  Map<int, OutboxMessage> conversionNewestMsgMap = {};
  for (OutboxMessage outboxMessage in outboxMessageList) {
    conversionNewestMsgMap[outboxMessage.conversationId!] = outboxMessage;
  }

  /// 对接收到的消息进行ack处理
  List<int> outboxMessageIdList =
      outboxMessageList.map((item) => item.id!).toList();
  await HttpUtils.batchACKOutboxMessage(outboxMessageIdList);

  /// 如果本地没有对应的会话，则从服务端查询并保存到本地
  List<int> conversationIdList =
      outboxMessageList.map((item) => item.conversationId!).toSet().toList();
  Result<List<Conversation>> conversationListResult =
      await HttpUtils.getConversationByIdList(conversationIdList);
  conversationListResult.data?.forEach((conversation) async {
    LocalConversation? localConversation =
        await LocalConversationService.getLocalConversationById(
            conversation.id!);
    if (localConversation == null) {
      OutboxMessage outboxMessage = conversionNewestMsgMap[conversation.id!]!;
      localConversation = LocalConversation.create(
          id: conversation.id,
          uid1: conversation.uid1,
          uid2: conversation.uid2,
          chatGroupId: conversation.chatGroupId,
          type: conversation.type,
          updateTime: DateTime.now().millisecondsSinceEpoch,
          newestMsgType: outboxMessage.messageType,
          newestMsg: outboxMessage.message,
          unreadMsgCount: 0);
      try {
        await LocalConversationService.addLocalConversation(localConversation);
      } on DatabaseException catch (ex) {
        logger.e(ex);
      }
    } else {
      OutboxMessage outboxMessage = conversionNewestMsgMap[conversation.id!]!;
      await LocalConversationService.setNewestMsg(
          localConversation.id,
          DateTime.now().millisecondsSinceEpoch,
          outboxMessage.message!,
          outboxMessage.messageType!);
    }
  });

  /// 设置用户未读消息数量
  await LocalConversationService.batchUpdateUnReadMsgCount(conversationIdList);

  /// 有新消息的时候，才更新全局状态
  GlobalStatus.instance.notify();
}
